# -*- coding: utf-8 -*-
"""
 Created by wq.wang on 2018/1/11
"""
import logging
from decimal import Decimal

from jsonschema import Draft4Validator

_logger = logging.getLogger(__name__)


def ensure_list(thing):
    """
    Wrap ``thing`` in a list if it's a single str.

    Otherwise, return it unchanged.

    """

    if isinstance(thing, str):
        return [thing]
    return thing


class DefValidator(Draft4Validator):
    """

    """

    def is_type(self, instance, type):
        if type == "boolean" and isinstance(instance, str) and instance.lower() in ('true', 'false'):
            return True
        if type == 'integer' and isinstance(instance, str):
            try:
                int(instance)
                return True
            except:
                return False
        if type == 'number' and isinstance(instance, str):
            try:
                float(instance)
                return True
            except:
                return False

        if type == 'string' and isinstance(instance, (float, int)):
            return True
        return super().is_type(instance, type)


def trans(schema, data):
    """
    转化为系统需要的参数类型
    :param schema:
    :param data:
    :return:
    """
    types = schema.get("type")
    if types == "object":
        for k, v in data.items():
            cschema = schema.get("properties", {}).get(k)
            if cschema:
                data[k] = trans(cschema, v)
        return data
    elif types == "array":
        new_data = []
        for a_data in data:
            new_data.append(trans(schema.get("items"), a_data))
        return new_data
    elif types == 'boolean':
        if isinstance(data, bool):
            return data
        elif isinstance(data, str) and data.lower() == 'true':
            return True
        else:
            return False
    elif types == "integer":
        return int(data)
    elif types == "string" and schema.get("format") == "decimal":
        return Decimal(data) if data else 0
    else:
        return data
